package ${domain}.frame.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import ${domain}.frame.excel.WHead;
import ${domain}.frame.excel.exception.TemplateNotMatchException;

import java.util.List;
import java.util.Map;


public abstract class WReadListener<T> extends AnalysisEventListener<T> {
    private List<WHead> wHeads;
    private TemplateNotMatchException[] es;
    private boolean isHead;

    public WReadListener(List<WHead> wHeads, TemplateNotMatchException[] es) {
        this.wHeads = wHeads;
        this.es = es;
        this.isHead = true;
    }

    @Override
    public void invokeHeadMap(Map headMap, AnalysisContext context) {
        if (wHeads.size() != headMap.size()) {
            es[0] = new TemplateNotMatchException("文件列数量与模板不一致!");
            return;
        }
        es[0] = null;
        for (int i = 0; i < wHeads.size(); i++) {
            WHead wCol = wHeads.get(i);
            String cellValue = headMap.get(i).toString();
            if (!wCol.getName().equals(cellValue)) {
                es[0] = new TemplateNotMatchException(String.format("第 %d 列应为[ %s ]", i + 1, wCol.getName()));
                break;
            }
        }
    }

    @Override
    public void invoke(T o, AnalysisContext analysisContext) {
        isHead = false;
        invoke(o);
    }

    public abstract void invoke(T o);

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    @Override
    public boolean hasNext(AnalysisContext context) {
        // 请求head
        if (isHead) {//多级表头，头部未结束
            return true;
        }
        if (!isHead && es[0] == null) {
            return true;
        }
        return false;
    }
}
